//
//  AppleScriptInterface.m
//  Pennyworth
//
//  Created by Chris Karr on 1/1/08.
//  Copyright 2008 Chris J. Karr. All rights reserved.
//

#import "AppleScriptInterface.h"
#import "Learner.h"

#import <Carbon/Carbon.h>

#define SCRIPT_PATH [NSString stringWithFormat:@"%@/Library/Application Support/Pennyworth/AppleScript", NSHomeDirectory ()]
#define TASK @"Task"

@implementation AppleScriptInterface

- (void) awakeFromNib
{
	cache = [[NSMutableDictionary alloc] init];
	labelTimers = [[NSMutableDictionary alloc] init];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processPrediction:) name:PREDICTION_FETCHED object:nil];
	
	[[NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(clearCaches:) userInfo:nil repeats:YES] retain];
}

- (void) clearCaches:(NSTimer *) theTimer
{
	[cache removeAllObjects];
}

- (void) processPrediction:(NSNotification *) note
{
	NSDictionary * userInfo = [note userInfo];

	BOOL update = NO;
	
	NSString * key = [userInfo valueForKey:KEY];
	NSObject * value = [userInfo valueForKey:PREDICTION];

	if (key == nil || value == nil)
		return;
		
	if (![value isEqual:[cache valueForKey:key]])
	{
		[cache setValue:value forKey:key];
		update = YES;
	}
		
	if (update)
	{
		NSTimer * labelTimer = [labelTimers valueForKey:key];
		
		if (labelTimer != nil)
			[labelTimer invalidate];

		labelTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(fire:) userInfo:
						[NSDictionary dictionaryWithObject:value forKey:key] repeats:NO];
		
		[labelTimers setValue:labelTimer forKey:key];
	}
}

- (void) fire:(NSTimer *) theTimer
{	
	NSDictionary * userInfo = [theTimer userInfo];
	
	NSString * key = [[userInfo allKeys] lastObject];
	NSObject * value = [userInfo valueForKey:key];

	NSFileManager * fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	
	if ([fm fileExistsAtPath:SCRIPT_PATH isDirectory:&isDir] && isDir)
	{
		NSArray * files = [[fm directoryContentsAtPath:SCRIPT_PATH] sortedArrayUsingSelector:@selector(compare:)];
		
		for (NSString * file in files)
		{
			if ([file hasSuffix:@".scpt"])
			{
				NSURL * scriptUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", SCRIPT_PATH, file]];				
				
				NSString * execPath = [[NSBundle mainBundle] pathForResource:@"Pennyworth Script Runner" ofType:@""];
				
				NSTask * task = [[NSTask alloc] init];
				[task setLaunchPath:execPath];
				[task setArguments:[NSArray arrayWithObjects:[scriptUrl description], key, value, nil]];
				[task launch];
				
				NSDictionary * userInfo = [NSDictionary dictionaryWithObject:task forKey:TASK];
				[[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(killTask:) userInfo:userInfo repeats:NO] retain];
			}
		}
	}
	else
		[fm createDirectoryAtPath:SCRIPT_PATH withIntermediateDirectories:YES attributes:nil error:nil];
}

- (void) killTask:(NSTimer *) theTimer
{
	NSTask * task = [[theTimer userInfo] objectForKey:TASK];
	
	if ([task isRunning])
	{
		// NSLog (@"task running, args = %@", [task arguments]);
		[task terminate];
	}
	// else
	//	NSLog (@"task finished, args = %@", [task arguments]);
			
	[task release];
	[theTimer release];
}
@end
